package cn.wolfcode.shop.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class ErrorResponseJSONFilter extends ZuulFilter {

    protected static final String SEND_ERROR_FILTER_RAN = "sendErrorFilter.ran";

    public String filterType() {
        return FilterConstants.ERROR_TYPE;
    }

    public int filterOrder() {
        return 0;
    }

    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.getThrowable()!=null
                && !ctx.getBoolean(SEND_ERROR_FILTER_RAN,false);
    }

    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        Map<String,String> map = new HashMap<>();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        response.setContentType("application/json;charset=UTF-8");
        if("true".equals(ctx.get("rateLimitExceeded"))){
            map.put("code","500501");
            map.put("msg","访问太快,请稍后再试");
            try {
                response.getWriter().write(JSON.toJSONString(map));
            } catch (IOException e) {
                e.printStackTrace();
            }
            //提示访问太快,请稍后再试.
            ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
            ctx.setSendZuulResponse(false);
        }else{
            map.put("code","500502");
            map.put("msg","系统繁忙");
            //系统异常
            try {
                response.getWriter().write(JSON.toJSONString(map));
            } catch (IOException e) {
                e.printStackTrace();
            }
            ctx.setResponseStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
            ctx.setSendZuulResponse(false);
        }

        return null;
    }
}
